//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    
  },
  
  onLoad: function () {
    /// 界面SKU原始数据
    let skuList = [
      {
        skuID: 1,           // skuID
        skuStock: 100,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/06f7e2cefe784b44bab1c7abf5e4483a.jpg',     // sku图片
        skuPrice: '50元',   // sku价格
        hasSelected: true,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '红色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '130',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '8分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 2
          }
        ]
      }, {
        skuID: 2,           // skuID
        skuStock: 200,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/c5fd8fa180264e0bade06b0af9ff3b6b.jpg',     // sku图片
        skuPrice: '100元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '红色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '90',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '9分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '1分',
            index: 2
          }
        ]
      }, {
        skuID: 3,           // skuID
        skuStock: 300,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/c5fd8fa180264e0bade06b0af9ff3b6b.jpg',     // sku图片
        skuPrice: '80元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '蓝色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '90',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '9分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '2分',
            index: 2
          }
        ]
      }, {
        skuID: 4,           // skuID
        skuStock: 300,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/36d80d82fd174b188f86b41d0f1dd695.jpg',     // sku图片
        skuPrice: '80元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '紫色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '90',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '9分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 2
          }
        ]
      }, {
        skuID: 5,           // skuID
        skuStock: 30,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/c5fd8fa180264e0bade06b0af9ff3b6b.jpg',     // sku图片
        skuPrice: '70元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '紫色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '110',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '7分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '3分',
            index: 2
          }
        ]
      }, {
        skuID: 6,           // skuID
        skuStock: 0,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/ecf1ebb1b525495781e0eb4b9ef9abc1.jpg',     // sku图片
        skuPrice: '140元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '粉色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '140',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '10分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '3分',
            index: 2
          }
        ]
      }, {
        skuID: 7,           // skuID
        skuStock: 30,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/f90a0e643eaf45f686c1e46b438f431a.jpg',     // sku图片
        skuPrice: '144元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '粉色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '130',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '9分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 3
          }
        ]
      }, {
        skuID: 8,           // skuID
        skuStock: 30,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/f90a0e643eaf45f686c1e46b438f431a.jpg',     // sku图片
        skuPrice: '149元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '粉色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '120',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '8分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 2
          }
        ]
      }, {
        skuID: 9,           // skuID
        skuStock: 30,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/f90a0e643eaf45f686c1e46b438f431a.jpg',     // sku图片
        skuPrice: '119元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '天蓝',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '120',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '8分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 2
          }
        ]
      }, {
        skuID: 10,           // skuID
        skuStock: 30,      // sku库存
        skuImgURL: 'http://pb9tpwgos.bkt.clouddn.com/f90a0e643eaf45f686c1e46b438f431a.jpg',     // sku图片
        skuPrice: '139元',   // sku价格
        hasSelected: false,  // 默认选中
        skuDetailList: [    // sku详情
          {
            detailTitle: '颜色',
            detailValue: '红色',
            index: 0
          }, {
            detailTitle: '尺码',
            detailValue: '120',
            index: 1
          }, {
            detailTitle: '长度',
            detailValue: '9分',
            index: 2
          }, {
            detailTitle: '哈哈',
            detailValue: '8分',
            index: 2
          }
        ]
      }
    ];

    /// 只处理库存大于0的场景
    skuList = skuList.filter(item => item.skuStock > 0);
    this.skuList = skuList;
    /// 最终拼凑的结构类似
    /*
    [
      {
        title: '颜色',
        values: [
          {
            isSelected: false,
            value: '红色'
          }, {
            isSelected: false,
            value: '蓝色'
          }, {
            isSelected: false,
            value: '粉色'
          }
        ]
      }
    ]
    */

    let uiSKUDataList = [];     // 与UI展示相关数据模型
    let uiSkuTitleSet = new Set(); // 所有skuTitle
    let uiSkuValueMap = new Map(); // 所有skuValue

    /// 1、提取所有的skuTitle
    for (let i = 0; i < skuList.length; i++) {
      let skuInfo = skuList[i] || {};
      let skuDetailList = skuInfo.skuDetailList || [];
      for (let j = 0; j < skuDetailList.length; j++) {
        let skuDetail = skuDetailList[j];
        
        if (!skuDetail || !skuDetail.detailTitle){
          continue;
        }
        
        uiSkuTitleSet.add(skuDetail.detailTitle);
        if (uiSkuValueMap.has(skuDetail.detailTitle)){
          let skuValues = uiSkuValueMap.get(skuDetail.detailTitle) || new Set();
          skuValues.add(skuDetail.detailValue);
          uiSkuValueMap.set(skuDetail.detailTitle, skuValues);
        } else {
          let skuValues = new Set();
          skuValues.add(skuDetail.detailValue);
          uiSkuValueMap.set(skuDetail.detailTitle, skuValues);
        }
      }
    }
    /// 2、将uiSkuTitleSet转成Array，根据skuTitle获取所有skuValue
    let uiSkuTitleArray = Array.from(uiSkuTitleSet);
    for(let i = 0; i < uiSkuTitleArray.length; i++){
      let uiSKUTitle = uiSkuTitleArray[i];
      let skuValues = Array.from(uiSkuValueMap.get(uiSKUTitle) || new Set()).map(item => {
        return {
          isSelected: false,  // 是否选中
          isEnabled: true,    // 是否可用
          value: item,        // 值
          icon: ''            // 改sku对应的icon
        }
      });

      let uiSKUData = {
        title: uiSKUTitle,
        values: skuValues
      };

      uiSKUDataList.push(uiSKUData);
    }

    // 处理选中sku与初始化固定数据
    uiSKUDataList = this.initSKUOptions(uiSKUDataList);

    // 处理禁用sku部分
    let handleResult = this.handleSKUOptions(uiSKUDataList);

    let handleUiSKUDataList = handleResult.uiSKUDataList;
    let handleSelectedSKU = handleResult.selectedSKU;

    this.setData({
      uiSKUDataList: handleUiSKUDataList,
      selectedSKU: handleSelectedSKU
    });
    this.setData({
      skuList: skuList
    });
  },

  /// 初始化sku信息
  initSKUOptions: function (uiSKUDataList){
    // 处理选中
    let skuList = this.skuList;
    // 只能有一个
    let selectedSkuList = skuList.filter(item => item.hasSelected);
    let selectedSku = {};
    if (selectedSkuList.length > 0){
      selectedSku = selectedSkuList[0];
    }
    
    uiSKUDataList = uiSKUDataList.map(item => {
      let innerItemList = item.values.map(innerItem => {
        innerItem.isSelected = selectedSku.skuDetailList.findIndex(skuDetail => {
          /// 选中的sku库存大于0 且 选中的sku的title与value 都等于目标
          return selectedSku.skuStock > 0 && skuDetail.detailValue == innerItem.value && skuDetail.detailTitle == item.title;
        }) >= 0;
        return innerItem;
      })
      item.values = innerItemList;
      return item;
    });
    
    return uiSKUDataList;
  },

  // 处理sku禁用部分
  handleSKUOptions: function (uiSKUDataList) {
    let skuList = this.skuList;

    let canSelectSkuList = skuList; // 可选的sku集合
    
    console.log('全部sku:', skuList);
    
    // 1、 获取所有选中的按钮，组合成为新的sku部分
    let selectOptions = [];
    for (let i = 0; i < uiSKUDataList.length; i++){
      let uiSKUData = uiSKUDataList[i];
      let title = uiSKUData.title;
      let value = (uiSKUData.values.find(item => item.isSelected) || {}).value;
      if(!value){
        continue;
      }
      selectOptions.push({
        detailTitle: title,
        detailValue: value
      });
    }

    // 2、 获取可选SKU
    canSelectSkuList = canSelectSkuList.filter(item => {
      let skuDetailList = item.skuDetailList;
      let isContain = true; // 每个sku是否包含选中的组合
      for (let i = 0; i < selectOptions.length; i++){
        let selOpt = selectOptions[i];
        let idx = skuDetailList.findIndex(item => item.detailTitle == selOpt.detailTitle && item.detailValue == selOpt.detailValue);
        if(idx < 0){
          isContain = false;
        }
      }
      return isContain;
    });

    // 2.1 拍平所有sku信息，组合成数组
    let canSelectSkuOptions = [];
    for (let i = 0; i < canSelectSkuList.length; i++){
      let canSelectSku = canSelectSkuList[i] || {};
      canSelectSkuOptions = canSelectSkuOptions.concat(canSelectSku.skuDetailList || []);
    }
    console.log('可选sku:', canSelectSkuList); 
    
    // 3、 禁用其他不在可选sku中的UI按钮选项
    for (let i = 0; i < uiSKUDataList.length; i++) {
      let uiSKURowData = uiSKUDataList[i];
      // 把每一行，可选的值全部拿出来
      let uiSKURowValueSet = new Set();
      /// 每一行的可选值
      let uiSKURowValueArray = [];
      for (let j = 0; j < canSelectSkuOptions.length; j++){
        let canSelectSkuOption = canSelectSkuOptions[j];
        if (canSelectSkuOption.detailTitle != uiSKURowData.title){
          continue;
        }
        uiSKURowValueSet.add(canSelectSkuOption.detailValue);
      }
      uiSKURowValueArray = Array.from(uiSKURowValueSet);
      uiSKURowData.values = uiSKURowData.values.map(item => {
        item.isEnabled = uiSKURowValueArray.findIndex(innerItem => {
          return innerItem == item.value;
        }) >= 0;
        return item;
      });
    }

    // 4、 如果只选中了一个选项按钮，则全部标记为可用
    if (selectOptions.length == 1){
      let selectOption = selectOptions[0];

      console.log(selectOption);
      for (let i = 0; i < uiSKUDataList.length; i++) {
        let uiSKUData = uiSKUDataList[i];
        if (uiSKUData.title != selectOption.detailTitle) {
          continue;
        }
        uiSKUData.values = uiSKUData.values.map(item => {
          item.isEnabled = true;
          return item;
        });
      }
    }

    return {
      uiSKUDataList: uiSKUDataList,       // sku选项信息
      selectedSKU: {}                 // 选中的sku
    };
  },

  onSKUItemTap: function(e) {
    let uiSKUDataList = this.data.uiSKUDataList;

    let item = e.currentTarget.dataset.item;
    let row = e.currentTarget.dataset.row;
    let column = e.currentTarget.dataset.column;
    
    if (!item.isEnabled) { return; }
    item.isSelected = !item.isSelected;
    uiSKUDataList[row].values = uiSKUDataList[row].values.map(item => {
      item.isSelected = false;
      return item;
    })
    uiSKUDataList[row].values[column] = item;
    
    // 处理禁用sku部分
    let handleResult = this.handleSKUOptions(uiSKUDataList);

    let handleUiSKUDataList = handleResult.uiSKUDataList;
    let handleSelectedSKU = handleResult.selectedSKU;

    this.setData({
      uiSKUDataList: handleUiSKUDataList,
      selectedSKU: handleSelectedSKU
    });
  }
  
})
